#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::FramelessWindowHint);

    pModel = new QStandardItemModel(ui->tableView);//实例化模型，并且指定模型依赖的控件
    ui->tableView->setModel(pModel);
    titles << "歌名" << "歌手" << "专辑" << "时长";
    QHeaderView * pHeaderView = ui->tableView->horizontalHeader();
    pHeaderView->setStyleSheet("QHeaderView::section{background-color:transparent}");
    ui->tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // 显示垂直滑动条
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // 平分
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);     //选中整行
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);      //不可更改

    playlist = new QMediaPlaylist;

    player = new QMediaPlayer;
    player->setPlaylist(playlist);
    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(slot_positionChanged(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(slot_durationChanged(qint64)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::paintEvent(QPaintEvent * event)
{
    QPainter painter(this);

    painter.drawPixmap(0,0,width(),height(),QPixmap(":/new/prefix1/pct/R-C.jfif"));
}


void MainWindow::replyFinished(QNetworkReply* reply)
{
    qDebug()<<"网页响应已完成"<<endl;
    QVariant ret = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<"网页返回状态为"<<ret<<endl;
    if(ret == 200)//200说明页面访问成功
    {
        QByteArray data = reply->readAll();//读取所有的网络数据
        parseJson(data);
    }
}

void MainWindow::parseJson(QByteArray jsonByte)
{
    QString songname_original2; //歌曲名
    QString singername2;        //歌手
    QString album_name2;        //专辑
    int duration2;          	//时间
    int music_id;               //音乐id

    QJsonParseError json_error;//JSON解析错误对象
    QJsonDocument parse_doucment = QJsonDocument::fromJson(jsonByte, &json_error);

    if (json_error.error == QJsonParseError::NoError)//判断解析过程是否有错误
    {
        if (parse_doucment.isObject())//判断文档是否是一个json对象
        {
            QJsonObject rootObj = parse_doucment.object();//获取文档JSON对象
            if (rootObj.contains("result"))//对象中是否包含键result
            {
                QJsonValue valuedata = rootObj.value("result");//获得result对应的值
                if (valuedata.isObject())//result对应的值是否是一个对象
                {
                    QJsonObject valuedataObject = valuedata.toObject();//把QJsonValue转为JsonObject对象
                    if (valuedataObject.contains("songs"))
                    {
                        QJsonValue valueArray = valuedataObject.value("songs");
                        if (valueArray.isArray())
                        {
                            //把结果转为QJsonArray数组才能遍历
                            QJsonArray array = valueArray.toArray();
                            int size = array.size();//(size>36?36:size)
                            for (int i = 0; i <=size; i++)
                            {
                                QJsonValue value = array.at(i);
                                if (value.isObject())
                                {
                                    //把数组的第i个元素变成一个JSON对象
                                    QJsonObject object = value.toObject();
                                    if (object.contains("album"))//专辑1
                                    {
                                        QJsonValue album_Object_1 = object.value("album");
                                        if (album_Object_1.isObject())
                                        {
                                            QJsonObject album_Object_1_tmp=album_Object_1.toObject();
                                            if(album_Object_1_tmp.contains("name"))
                                            {
                                                QJsonValue ID_value = album_Object_1_tmp.value("name");
                                                if (ID_value.isString())
                                                {
                                                    album_name2 = ID_value.toString();
                                                }
                                            }
                                        }
                                    }
//                                    if (object.contains("alias"))//专辑2
//                                    {
//                                        QJsonValue Album_value_tmp = object.value("alias");
//                                        if (Album_value_tmp.isArray())
//                                        {
//                                            QJsonArray Album_value_array=Album_value_tmp.toArray();
//                                            if(Album_value_tmp.isArray())
//                                            {
//                                                if(Album_value_array.at(0).toString()!="")
//                                                    album_name2 = Album_value_array.at(0).toString()+"(别名)";
//                                            }
//                                        }
//                                    }
                                    if (object.contains("artists"))//歌手
                                    {
                                        QJsonValue artists_value_tmp = object.value("artists");
                                        if(artists_value_tmp.isArray())
                                        {
                                            QJsonArray artists_array = artists_value_tmp.toArray();
                                            int artists_size=artists_array.size();
                                            for(int k=0;k<artists_size;k++)
                                            {
                                                QJsonValue artists_name=artists_array.at(k);
                                                if(artists_name.isObject())
                                                {
                                                    QJsonObject artists_name_object=artists_name.toObject();
                                                    if(artists_name_object.contains("name"))
                                                    {
                                                        QJsonValue artistsname = artists_name_object.take("name");
                                                        if (artistsname.isString())
                                                        {
                                                            if(k==0)
                                                            {
                                                                singername2 = artistsname.toString();
                                                            }
                                                            else
                                                            {
                                                                singername2 = singername2 + "/" +artistsname.toString();
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (object.contains("name"))//歌曲名
                                    {
                                        QJsonValue Album_ID_value = object.take("name");
                                        if (Album_ID_value.isString())
                                        {
                                            songname_original2 = Album_ID_value.toString();
                                        }
                                    }
                                    if (object.contains("duration"))//时长
                                    {
                                        QJsonValue AlbumID_value = object.take("duration").toInt();
                                        duration2 = AlbumID_value.toInt();
                                        duration2=duration2/1000;
                                    }
                                    if (object.contains("id"))//歌曲id
                                    {
                                        QJsonValue FileHash_value = object.take("id");
                                        if (!FileHash_value.isNull())
                                        {
                                            //用Vector保存每首歌曲的album_id
                                            music_id=FileHash_value.toInt();
                                        }
                                    }
                                    song _song;
                                    _song.album_name = album_name2;
                                    _song.singer = singername2;
                                    _song.songname = songname_original2;
                                    _song.duration2 = duration2;
                                    _song.music_id = music_id;
                                    song_List.push_back(_song);

                                    //构建歌曲播放链接
                                    QString play_url = QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(music_id);
                                    playlist->addMedia(QUrl(play_url));//把歌曲加入到播放列表

                                    pModel->setHorizontalHeaderLabels(titles);
                                    QList<QStandardItem *> sti;

                                    sti<< new QStandardItem(songname_original2)<< new QStandardItem(singername2)<< new QStandardItem(album_name2)<<new QStandardItem(QString().number(duration2));

                                    pModel->appendRow(sti);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    else
    {
        qDebug() << json_error.errorString();
    }

    for(int i = 0 ; i < song_List.size() ; i++)
    {
        song _song = song_List[i];
        qDebug()<<_song.album_name<<" "<<_song.singer<<" "<<_song.songname<<" "<<_song.duration2<<" "<<_song.music_id<<endl;
    }
}

void MainWindow::on_pushButton_close_clicked()
{
    close();
}

void MainWindow::on_pushButton_clicked()
{
    pModel->clear();
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));
    manager->get(QNetworkRequest( QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(ui->lineEdit->text()) ) ) );


}

void MainWindow::on_tableView_doubleClicked(const QModelIndex &index)
{
    playlist->setCurrentIndex(index.row());//双击的行数就是播放列表中歌曲的下标
    player->play();
}

void MainWindow::slot_positionChanged(qint64 position)
{
    qDebug()<<position<<endl;
    ui->horizontalSlider->setValue(position);

}

void MainWindow::slot_durationChanged(qint64 duration)
{
    qDebug()<<"开始播放一首新歌，总时长为："<<duration<<endl;
    qint64 seconds = duration / 1000;
    qint64 minutes = seconds / 60;
    seconds %= 60; // 计算剩余的秒数

    // 格式化字符串
    QString timeString = QString("%1:%2").arg(minutes, 2, 10, QChar('0')).arg(seconds, 2, 10, QChar('0'));

    ui->lineEdit_2->setText(timeString);
    ui->horizontalSlider->setRange(0,duration);
}


void MainWindow::on_horizontalSlider_actionTriggered(int action)
{
    int ret = ui->horizontalSlider->value();
    player->setPosition(ret);
}

void MainWindow::on_pushButton_2_clicked()
{
    if(player->state() == QMediaPlayer::PlayingState)
    {
        player->pause();
    }
    else
    {
        player->play();
    }
}

void MainWindow::on_pushButton_3_clicked()
{
    this->close();
    Form *s = new Form;
    player->stop();
    s->show();
}
